﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using MINERP.COM;
using MINERP.DAL;
using MINERP.DAL.InnerReturn;
using MINERP.MODEL.FoundationModel;
using System.Data;

namespace MINERP.BLL.InnerReturn
{
    public class InnerReturnBLL
    {
        private DAL.InnerReturn.InnerReturnDAL _dal = new InnerReturnDAL();
        /// <summary>
        /// 取得照片信息
        /// </summary>
        /// <param name="inBarCode"></param>
        /// <returns></returns>
        public PhotoView GetPhotoViewByBarCode(string inBarCode)
        {
            BLL.InnerReturn.PhotoView photoView = new PhotoView();
            photoInfo info = _dal.GetPhotoByBarCode(inBarCode);
            if (info == null)
            {
                return null;
            }
            photoView.Photo = new PhotoInfo_Info() { Height = info.Height, Width = info.Width, PhotoBarCode = info.PhotoBarCode, PhotoId = info.photoId, PhotoName = info.photoName, PicPath = info.picPath };
            if (!info.orderInfoReference.IsLoaded)
            {
                info.orderInfoReference.Load();
            }
            orderInfo product = info.orderInfo;

            photoView.Product = new OrderInfo_Info() { OrderProductCode = product.OrderProductCode, OrderProductId = product.OrderProductId, OrderProductName = product.OrderProductName };
            return photoView;
        }
        /// <summary>
        /// 根据格子ID查找产品信息
        /// </summary>
        /// <param name="inGridId"></param>
        /// <returns></returns>
        public int GetProductIDByGridId(int inGridId)
        {
            return _dal.GetProductIDByGridId(inGridId);
        }

        /// <summary>
        /// 取得流程节点信息
        /// </summary>
        /// <param name="inProductId"></param>
        /// <returns></returns>
        public List<Tb_Tech_Info> GetProductFlowByProduct(int inProductId)
        {
            List<WorkOrderFlowList> flowLists = _dal.GetFlowsByProduct(inProductId);

            List<Tb_Tech_Info> listInfos = new List<Tb_Tech_Info>();
            foreach (WorkOrderFlowList list in flowLists)
            {
                if (!list.tb_TechReference.IsLoaded)
                {
                    list.tb_TechReference.Load();
                }
                Tb_Tech_Info techInfo = new Tb_Tech_Info() { TechId = list.tb_Tech.TechId, TechName = list.tb_Tech.TechName };
                listInfos.Add(techInfo);
            }
            return listInfos;
        }
        /// <summary>
        /// 取到所有的用户列表
        /// </summary>
        /// <returns></returns>
        public List<User_Info> GetAllUsers()
        {

            List<users> userList = _dal.GetAllUsers();
            List<User_Info> infos = new List<User_Info>();
            foreach (users user in userList)
            {
                User_Info info = new User_Info();
                info = new User_Info() { UserID = user.userID, UserName = user.UserName };
                infos.Add(info);
            }
            return infos;
        }
        /// <summary>
        /// 取到所有节点名称
        /// </summary>
        /// <returns></returns>
        public List<Tb_Tech_Info> GetAllTech()
        {
            List<tb_Tech> techs = _dal.GetAllTechs();
            List<Tb_Tech_Info> infos = new List<Tb_Tech_Info>();
            foreach (tb_Tech list in techs)
            {
                Tb_Tech_Info info = new Tb_Tech_Info() { TechId = list.TechId, TechName = list.TechName };

                ////福州屏蔽输出管理
                //if (info.TechName.Equals("输出管理"))
                //{
                //    continue;
                //}
                infos.Add(info);
            }
            return infos;
        }
        /// <summary>
        /// 取得返工流程
        /// </summary>
        /// <param name="inEndId"></param>
        /// <param name="inProductId"></param>
        /// <returns></returns>
        public List<Tb_Tech_Info> GetReturnList(int inEndId, int inProductId)
        {
            List<WorkOrderFlowList> flowLists = _dal.GetFlows(inProductId, inEndId);
            List<Tb_Tech_Info> infos = new List<Tb_Tech_Info>();
            foreach (WorkOrderFlowList list in flowLists)
            {
                list.tb_TechReference.Load();
                tb_Tech tech = list.tb_Tech;
                Tb_Tech_Info info = new Tb_Tech_Info() { TechId = tech.TechId, TechName = tech.TechName };
                infos.Add(info);
            }
            return infos;

        }
        /// <summary>
        /// 建立内部返工产品和流程
        /// </summary>
        /// <param name="inProductId">返单产品ID</param>
        /// <param name="inTechs">返工流程</param>
        /// <param name="inPhotoList">返工照片列表</param>
        /// <param name="inOperId">当前操作人</param>
        /// <param name="inReturnUserid">返单责任人</param>
        /// <param name="inRemark">返单备注</param>
        /// <param name="inReturnTechId">返工责任流程</param>
        /// <param name="OriginateUserID">返工发起人</param>
        public void CreateReturnOrder(int inProductId, List<Tb_Tech_Info> inTechs, List<PhotoView> inPhotoList, int inOperId, int inReturnUserid, string inRemark, int inReturnTechId, int inOriginateUserID)
        {
            orderInfo productParent = _dal.GetProductbyId(inProductId);
            productParent.Tb_OrderBagReference.Load();
            productParent.Tb_ProductReference.Load();
            Tb_OrderBag orderBag = productParent.Tb_OrderBag;
            Tb_Product productType = productParent.Tb_Product;
            System.Transactions.TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                orderInfo newProduct = new orderInfo();
                newProduct.CompleteTime = DateTime.Now;
                newProduct.CtmName = productParent.CtmName;
                newProduct.Height = productParent.Height;
                newProduct.IsEdit = false;
                newProduct.OrderPath = productParent.OrderPath;
                newProduct.OrderProductCode = productParent.OrderProductCode;
                newProduct.OrderProductName = productParent.OrderProductName + "内部返工";
                newProduct.OrilOrderPath = productParent.OrilOrderPath;                       //订单内照片的原始目录
                newProduct.PageNum = productParent.PageNum;
                newProduct.productNum = 1;//只反一一个产品
                newProduct.Remark = productParent.Remark;
                newProduct.status = productParent.status;                     //产品的状态                    
                newProduct.Tb_OrderBag = productParent.Tb_OrderBag;
                newProduct.Priority = 10;//目前最高级别
                newProduct.Tb_Product = productParent.Tb_Product;
                newProduct.Width = productParent.Width;
                newProduct.ParentProductId = productParent.OrderProductId;
                newProduct.ProductType = (int)OrderProductType.InnerReturn;
                //关联照片
                List<photoInfo> newPhotoList = new List<photoInfo>();
                foreach (PhotoView list in inPhotoList)
                {
                    photoInfo photoOld = _dal.GetPhotoById(list.PhotoId);
                    photoInfo newPhoto = new photoInfo();

                    photoOld.orderInfoReference.Load();
                    photoOld.paperFaceReference.Load();
                    photoOld.paperTypeReference.Load();
                    photoInfo photo = new photoInfo();
                    photo.Height = photoOld.Height;
                    photo.IsModifySize = photoOld.IsModifySize;
                    photo.MakeUpNum = photoOld.MakeUpNum;
                    photo.OldPicPath = photoOld.OldPicPath;
                    photo.orderInfo = newProduct;//新建照片属于新建的产品

                    photo.paperFace = photoOld.paperFace;
                    photo.paperType = photoOld.paperType;
                    photo.PhotoBarCode = photoOld.PhotoBarCode;
                    //photo.photoId = photoOld.photoId; 只有ID不同
                    photo.photoName = photoOld.photoName;
                    //photo.picMakeUp = photoOld.picMakeUp;
                    photo.picPath = photoOld.picPath;
                    photo.pixHeight = photoOld.pixHeight;
                    photo.pixWidth = photoOld.pixWidth;
                    //photo.printerId = photoOld.printerId;
                    photo.printerId = 0;
                    photo.TotalNum = 1;//一个产品
                    photo.Width = photoOld.Width;
                    // photo.status = (int)PhotoStatus.PhotoInnerReturn;
                    photo.Remark = photoOld.Remark;
                    photo.status = (int)PhotoStatus.NoDistributePrinter;///新照片状态复原
                    photoOld.status = (int)PhotoStatus.PhotoInnerReturn;///旧照片状态到返单

                }

                //List<photoInfo> photoInfos = oi.photoInfo.ToList();


                //foreach (photoInfo list in photoInfos)
                //{
                //    list.orderInfoReference.Load();
                //    list.paperFaceReference.Load();
                //    list.paperTypeReference.Load();
                //    photoInfo photo = new photoInfo();
                //    photo.Height = list.Height;
                //    photo.IsModifySize = list.IsModifySize;
                //    photo.MakeUpNum = list.MakeUpNum;
                //    photo.OldPicPath = list.OldPicPath;
                //    photo.orderInfo = list.orderInfo;
                //    photo.paperFace = list.paperFace;
                //    photo.paperType = list.paperType;
                //    photo.PhotoBarCode = list.PhotoBarCode;
                //    photo.photoId = list.photoId;
                //    photo.photoName = list.photoName;
                //    photo.picMakeUp = list.picMakeUp;
                //    photo.picPath = list.picPath;
                //    photo.pixHeight = list.pixHeight;
                //    photo.pixWidth = list.pixWidth;
                //    photo.printerId = list.printerId;
                //    photo.TotalNum = list.TotalNum;
                //    photo.status = list.status;
                //    photo.Remark = list.Remark;
                //    list.orderInfo = parentProduct;//该回原来的产品
                //    photo.orderInfo = oi;//返单添加的产品

                //}

                //关联流程
                DateTime lastTechTime = DateTime.Now;                //上个节点的完成时间
                //double techNeedTime = Convert.ToDouble(work.tb_Tech.NeedTime);
                int i = 0;// 要激活流程
                foreach (Tb_Tech_Info info in inTechs)
                {
                    tb_Tech tech = _dal.GetTechById(info.TechId);
                    WorkOrderFlowList newFlow = new WorkOrderFlowList();
                    newFlow.tb_Tech = tech;
                    newFlow.WorkOrder = tech.WokerOrder;
                    newFlow.orderInfo = newProduct;
                    newFlow.UserId = 0;
                    newFlow.AssignTime = lastTechTime;
                    newFlow.ReceiveTime = lastTechTime;
                    newFlow.PreCompleteTime = Convert.ToDateTime(newFlow.ReceiveTime).AddHours(tech.NeedTime);
                    newFlow.CompletedTime = newFlow.PreCompleteTime;
                    lastTechTime = Convert.ToDateTime(newFlow.CompletedTime);
                    if (i == 0)
                    {
                        newFlow.Status = (int)OrderFlowListStatus.Useable;
                    }
                    else
                    {
                        newFlow.Status = (int)OrderFlowListStatus.Wait;
                    }
                    newProduct.WorkOrderFlowList.Add(newFlow);
                    i++;

                }
                //父产品停止 子产品激活
                newProduct.status = (int)OrderInfoStatus.Doing;
                productParent.status = (int)OrderInfoStatus.Stop;
                _dal.SaveDate();
                InnerReturnOrder innerReturnOrder = new InnerReturnOrder();
                innerReturnOrder.orderInfo = productParent;
                innerReturnOrder.tb_Tech = _dal.GetTechById(inReturnTechId);
                innerReturnOrder.ReturnUid = inReturnUserid;
                //innerReturnOrder.
                innerReturnOrder.Remark = inRemark;
                innerReturnOrder.CreateTime = DateTime.Now;
                innerReturnOrder.CreateUid = inOperId;
                innerReturnOrder.status = (int)InnerReturnOrderStatus.Use;
                innerReturnOrder.OriginateUserID = inOriginateUserID;
                innerReturnOrder.ChildOrderProductid = newProduct.OrderProductId;
                _dal.insert(innerReturnOrder);
                _dal.SaveDate();
                scope.Complete();
            }

        }
        /// <summary>
        /// 取得正在进行的流程
        /// </summary>
        /// <param name="inProductId"></param>
        /// <returns></returns>
        public Tb_Tech_Info GetCurrTech(int inProductId)
        {
            orderInfo order = _dal.GetProductbyId(inProductId);
            order.WorkOrderFlowList.Load();
            Tb_Tech_Info info = new Tb_Tech_Info();
            List<WorkOrderFlowList> listFlow = order.WorkOrderFlowList.ToList();
            foreach (WorkOrderFlowList flow in listFlow)
            {
                if (flow.Status == (int)OrderFlowListStatus.Useable)
                {
                    flow.tb_TechReference.Load();
                    info.TechId = flow.tb_Tech.TechId;
                    info.TechName = flow.tb_Tech.TechName;
                    break;
                }

            }
            return info;
        }
        /// <summary>
        /// 正在返工返回true
        /// </summary>
        /// <param name="inPhotoBarcode"></param>
        /// <returns></returns>
        public bool IsFandanIng(string inPhotoBarcode)
        {
            return _dal.IsFanDanIng(inPhotoBarcode);
        }


        /// <summary>
        /// 取得用户名称
        /// </summary>
        /// <param name="inProductId"></param>
        /// <param name="inTechId"></param>
        /// <returns></returns>
        public User_Info GetUser(int inProductId, int inTechId)
        {
            users use = _dal.GetUser(inProductId, inTechId);
            if (use == null)
            {
                return null;
            }
            return new User_Info() { UserID = use.userID, UserName = use.UserName };
        }
        public User_Info GetUser(int inTechId)
        {
            users use = _dal.GetUser( inTechId);
            if (use == null)
            {
                return null;
            }
            return new User_Info() { UserID = use.userID, UserName = use.UserName };
        }
        public List<User_Info> GetUsersByTech(int inTechid)
        {
            List<User_Info> rtnUsers = new List<User_Info>();

            List<users> listUser = _dal.GetUsersByTechId(inTechid);
            foreach (users list in listUser)
            {
                User_Info info = new User_Info();
                info = new User_Info() { UserID = list.userID, UserName = list.UserName };
                rtnUsers.Add(info);

            }
            return rtnUsers;
        }

        public DataTable GetUnComplteFanDan()
        {
            return _dal.GetUnComplteFanDan();
        }

        public DataTable GetPhotosByProductID(int inProductId)
        {
            return _dal.GetPhotosByProductID(inProductId);
        }

        public int ActionMainProduct(int inChildProductID)
        {
            //using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            //{
            newSampleYPDBEntities db = DALBase.DataEntites;
            System.Transactions.TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, options))
            {
                int parentType = (int)OrderProductType.Normal;
                int intDoing = (int)OrderInfoStatus.Doing;
                int intComplete = (int)OrderInfoStatus.Completed;
                int intZanTing = (int)OrderInfoStatus.Stop;

                int intPhotoInGrid = (int)PhotoStatus.FenPian;
                int intPhotoUnGrid = (int)PhotoStatus.Printed;

                int intWorkFlowComplete = (int)OrderFlowListStatus.Complete;
                orderInfo oi = db.orderInfo.Where(p => p.OrderProductId == inChildProductID).FirstOrDefault();

                if (oi == null)
                {
                    return -1;
                }
                else
                {
                    if (oi.ProductType == parentType)//如果是主产品
                    {
                        List<orderInfo> listchildProduct = db.orderInfo.Where(p => p.ParentProductId == inChildProductID).ToList();
                        foreach (orderInfo child in listchildProduct)
                        {
                            if (!child.photoInfo.IsLoaded)
                            {
                                child.photoInfo.Load();
                            }
                            List<photoInfo> listPhoto = child.photoInfo.ToList();
                            ////子产品的所有照片标志完成
                            foreach (photoInfo photo in listPhoto)
                            {
                                photo.PhotoBarCode = "3" + string.Format("{0:D9}", photo.photoId);
                                photo.status = intPhotoInGrid;
                            }
                            child.status = intComplete;
                            if (!child.WorkOrderFlowList.IsLoaded)
                            {
                                child.WorkOrderFlowList.Load();
                            }
                            ////子产品的所有流程标志完成
                            List<WorkOrderFlowList> listWorkFlow = child.WorkOrderFlowList.ToList();
                            foreach (WorkOrderFlowList work in listWorkFlow)
                            {
                                if (work.Status != intWorkFlowComplete)
                                    work.Status = intWorkFlowComplete;
                            }

                        }
                        //修改主产品的照片状态
                        if (!oi.WorkOrderFlowList.IsLoaded)
                        {
                            oi.WorkOrderFlowList.Load();
                        }
                        WorkOrderFlowList listMainFenPian = oi.WorkOrderFlowList.FirstOrDefault(p => p.tb_Tech.TechId <= 8 && p.Status == 1);//

                        if (!oi.photoInfo.IsLoaded)
                        {
                            oi.photoInfo.Load();
                        }
                        List<photoInfo> listPhotoMain = oi.photoInfo.ToList();
                        foreach (photoInfo photo in listPhotoMain)
                        {
                            if (listMainFenPian != null)//分片为界
                            {
                                if (photo.status != intPhotoInGrid)
                                {
                                    photo.status = intPhotoUnGrid;//未进格子
                                }
                            }
                            else
                            {
                                photo.status = intPhotoInGrid;//已经完成
                            }
                        }
                        oi.status = intDoing;
                    }

                    else
                    {
                        oi.status = intComplete;//如果是子产品子产品完成
                        orderInfo listProduct = db.orderInfo.Where(p => p.ParentProductId == oi.ParentProductId).ToList().Where(p => p.status == intDoing).FirstOrDefault();
                        orderInfo oiParent = db.orderInfo.Where(p => p.OrderProductId == oi.ParentProductId).FirstOrDefault();
                        if (listProduct == null)//没有子产品在生产
                        {

                            if (!oiParent.photoInfo.IsLoaded)
                            {
                                oiParent.photoInfo.Load();
                            }

                            //修改住产品照片状态
                            if (!oiParent.WorkOrderFlowList.IsLoaded)
                            {
                                oiParent.WorkOrderFlowList.Load();
                            }
                            WorkOrderFlowList listMainFenPian = oiParent.WorkOrderFlowList.FirstOrDefault(p => p.tb_Tech.TechId <= 8 && p.Status == 1);//
                            if (!oiParent.photoInfo.IsLoaded)
                            {
                                oiParent.photoInfo.Load();
                            }
                            List<photoInfo> listPhotoMain = oiParent.photoInfo.ToList();
                            foreach (photoInfo photo in listPhotoMain)
                            {
                                if (listMainFenPian != null)//分片为界
                                {
                                    if (photo.status != intPhotoInGrid)
                                    {
                                        photo.status = intPhotoUnGrid;//未进格子
                                    }
                                }
                                else
                                {
                                    photo.status = intPhotoInGrid;//已经完成
                                }
                            }
                            oiParent.status = intDoing;//修改父产品状态

                        }
                        else
                        {
                            oiParent.status = intZanTing;//修改父产品状态
                        }
                        //修改字产品的照片状态
                        if (!oi.photoInfo.IsLoaded)
                        {
                            oi.photoInfo.Load();
                        }
                        List<photoInfo> listPhotoOi = oi.photoInfo.ToList();
                        foreach (photoInfo photo in listPhotoOi)
                        {
                            photo.PhotoBarCode = "3" + string.Format("{0:D9}", photo.photoId);
                            photo.status = intPhotoInGrid;
                        }
                        ////子产品的所有流程标志完成
                        if (!oi.WorkOrderFlowList.IsLoaded)
                        {
                            oi.WorkOrderFlowList.Load();
                        }
                        List<WorkOrderFlowList> listWorkFlow = oi.WorkOrderFlowList.ToList();
                        foreach (WorkOrderFlowList work in listWorkFlow)
                        {
                            if (work.Status != intWorkFlowComplete)
                                work.Status = intWorkFlowComplete;
                        }
                    }

                }
                db.SaveChanges();
                ts.Complete();
            }
            return 0;
        }

    }
}
